package com.solarStruggle.domain

import java.io.{File, FilenameFilter, FileInputStream, FileOutputStream, IOException, ObjectInputStream, ObjectOutputStream, ObjectStreamException, Serializable}
import util.{Random}

@serializable
class Game(_name: String, 
           _solarSystems: Array[SolarSystem], 
           _wormholes: Array[Wormhole]) {

  val name = _name
  val galaxy = new Galaxy(_solarSystems, _wormholes)
}

object GameCreator {
  
  private val ssDataDir = new File(System.getProperty("user.home") + "/.solarStruggle")
  
  def all: Seq[String] = {
    return ssDataDir.list(new FilenameFilter {
      def accept(dir: File, filename: String): boolean = filename.endsWith(".ss")
    })
  }
  
  def load(name: String): Game = {
    return new ObjectInputStream(new FileInputStream(new File(ssDataDir, name + ".ss"))).readObject.asInstanceOf[Game]
  }
  
  /**
   * Saves a game to disk
   */
  def save(game: Game) {
    ssDataDir.mkdirs()
    val output = new ObjectOutputStream(new FileOutputStream(new File(ssDataDir, game.name + ".ss")))
    println(game.getClass.getName)
    output.writeObject(game)
    output.close()
  }
  
  
  def apply(name: String, numSolarSystems: int, numConnections: int, solarSystemSize: int): Game = {
    val r = new Random()
    val solarSystems = new Array[SolarSystem](numSolarSystems)
    for(i <- 0 until numSolarSystems) {
      solarSystems(i) = SolarSystem(solarSystemSize, r.nextInt(Galaxy.Size), r.nextInt(Galaxy.Size))
    }
    val wormholes = new Array[Wormhole](numConnections)
    for(i <- 0 until numConnections) {
      wormholes(i) = new Wormhole(r.nextInt(numSolarSystems), r.nextInt(numSolarSystems))
    }
    
    new Game(name, solarSystems, wormholes)
  }
}
